package org.whatever.aha.zjut.platform.aspect;

import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.beetl.android.internal.util.ArrayUtils;
import org.springframework.stereotype.Component;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.annotation.ProjectPermission;
import org.whatever.aha.zjut.platform.service.StudentInfoService;
import org.whatever.aha.zjut.platform.service.project.ProjectMemberService;
import org.whatever.aha.zjut.platform.service.project.ProjectService;

/**
 * @author Vc
 * @version 1.0
 * @Desc 项目普通校验切面类
 * @date 2021/09/26 0:06
 */
@Aspect
@Component
@RequiredArgsConstructor
public class OperationPermissionAspect {
    final ProjectService projectService;
    final StudentInfoService studentInfoService;
    final ProjectMemberService projectMemberService;

    @Pointcut("@annotation(projectPermission)")
    public void pointCut(ProjectPermission projectPermission) throws AppException {
    }

    @Before(value = "pointCut(projectPermission)", argNames = "joinpoint,projectPermission")
    public void before(JoinPoint joinpoint, ProjectPermission projectPermission) {
        int curUserId = StpUtil.getLoginIdAsInt();
        MethodSignature methodSignature = (MethodSignature) joinpoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        int projectIdIdx = ArrayUtils.indexOf(parameterNames, "projectId");
        int pid = (int) joinpoint.getArgs()[projectIdIdx];
        //先判断项目、用户是否存在
        if (projectService.getLeaderId( pid) != null){
            if (!studentInfoService.existUserId(curUserId)) {
                throw new AppException(ErrorCode.USER_NOT_EXIST,null);
            }
        }else {
            throw new AppException(ErrorCode.PROJECT_NOT_EXIST,null);
        }
        //判断是否有权限操作
        if (!projectService.hasPermission(curUserId, pid)) {
            throw new AppException(ErrorCode.OPERATION_NOT_AUTHORIZED,null);
        }
    }
}
